/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.muni.fi.pa165.ddtroops.entities;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *  Class EntityBuilder is a generic class used to create
 *  entities quicker as opposed to using of constructors, setters etc.
 * 
 * @author Matěj
 */
public class EntityBuilder<T>
{
    private T object;
    private Class<T> clazz;

    public EntityBuilder(Class<T> clazz)
    {
        this.clazz = clazz;
        try {
            object = clazz.newInstance();
        } catch (Exception ex) {
            Logger.getLogger(EntityBuilder.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    public EntityBuilder<T> withProperty(String fieldName, Object value)
    {
        try {
            StringBuilder sb = new StringBuilder();
            String name = sb.append("set")
                    .append(Character.toUpperCase(fieldName.charAt(0)))
                    .append(fieldName.substring(1)).toString();
            for (Method m : clazz.getMethods()) {
                if(m.getName().equals(name)) m.invoke(object, value);
            }
        } catch (Exception ex) {
            Logger.getLogger(EntityBuilder.class.getName()).log(Level.SEVERE, null, ex);
        }
        return this;
    }
    
    public EntityBuilder<T> withField(String fieldName, Object value)
    {
        try {
            for (Field f : clazz.getFields()) {
                if(f.getName().equals(fieldName)) f.set(object, value);
            }
        } catch (Exception ex) {
            Logger.getLogger(EntityBuilder.class.getName()).log(Level.SEVERE, null, ex);
        }
        return this;
    }
    
    public T Build()
    {
        return object;
    }
}
